package casa.depesos.app.com.frag;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.common.base.task.SilentTask;
import com.common.base.task.TaskEngine;
import com.zhpan.bannerview.BannerViewPager;

import java.util.ArrayList;
import java.util.List;

import casa.depesos.app.com.App;
import casa.depesos.app.com.R;
import casa.depesos.app.com.activity.MainActivity;
import casa.depesos.app.com.activity.WebActivity;
import casa.depesos.app.com.adapter.BannerAdapter;
import casa.depesos.app.com.databinding.CountDownBinding;
import casa.depesos.app.com.databinding.HomeTopBinding;
import casa.depesos.app.com.databinding.MeTouchBinding;
import casa.depesos.app.com.databinding.MsgPartBinding;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.BannerBean;
import casa.depesos.app.com.http.bean.LinkInfoBean;
import casa.depesos.app.com.http.bean.NameBean;
import casa.depesos.app.com.http.data.Banner;
import casa.depesos.app.com.http.data.Msg;
import casa.depesos.app.com.http.req.BannerReq;
import casa.depesos.app.com.http.req.LinkInfoReq;
import casa.depesos.app.com.http.req.MsgReq;
import casa.depesos.app.com.http.req.NameReq;
import casa.depesos.app.com.http.req.UnReadReq;
import casa.depesos.app.com.it.BannerClickListener;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public abstract class BannerBaseFragment extends BaseFragment implements BannerClickListener {

    boolean initPager = false;
    protected String email;

    protected String getBannerType() {
        return "1";
    }

    protected void getBanner(BannerViewPager pager) {
        new BannerReq(getBannerType()).req(new ReqCallback<BannerBean>() {
            @Override
            public void callback(boolean success, BannerBean bean) {
                if (success && bean.isValid()) {
                    setBanner(bean.list, pager);
                }
            }
        });
    }

    private void setBanner(List<Banner> list, BannerViewPager pager) {
        Glide.with(this).load(list.get(0).img).addListener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                Bitmap bm = ((BitmapDrawable) resource).getBitmap();
                int w = bm.getWidth();
                int h = bm.getHeight();
                h = (int) (h * 1f / w * (Utils.getScreenWidth() - Utils.dp2Px(App.getApp(), 30)));
                pager.getLayoutParams().height = h;
                pager.setVisibility(View.VISIBLE);
                if (!initPager) {
                    initPager = true;
                    pager.setLifecycleRegistry(getLifecycle())
                            .setAdapter(new BannerAdapter(BannerBaseFragment.this))
                            .create(list);
                }
                pager.setAutoPlay(true);
                return true;
            }
        }).preload();
    }

    @Override
    public void onBannerClick(Banner banner) {
        if (this instanceof HomeFragment) {
            Report.click("ACTION_HH_003");
        } else if (this instanceof TakeCheckOkFragment) {
            Report.click("ACTION_SS_007");
        } else if (this instanceof TakeCheckFragment) {
            Report.click("ACTION_SS_002");
        } else if (this instanceof TakeFailFragment) {
            Report.click("ACTION_SS_005");
        }
        WebActivity.toSysWeb(banner.url);
    }

    private void toMsg() {
        Utils.toMsg();
    }

    protected void showMsg(MsgPartBinding binding, View next) {
        binding.getRoot().setVisibility(View.INVISIBLE);
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                List<Msg> list = new MsgReq("SYSTEM", Integer.MAX_VALUE).req();
                h.post(() -> showMsg(binding, list, next));
            }
        });
    }

    private void showMsg(MsgPartBinding binding, List<Msg> list, View next) {
        if (list == null || list.isEmpty()) {
            binding.msgs.setVisibility(View.GONE);
            ((ViewGroup.MarginLayoutParams) next.getLayoutParams()).topMargin = 0;
        } else {
            binding.getRoot().setVisibility(View.VISIBLE);
            ((ViewGroup.MarginLayoutParams) next.getLayoutParams()).topMargin = Utils.dp2Px(App.getApp(), 45);
            binding.msgs.setVisibility(View.VISIBLE);
            Msg msg = list.get(0);
            binding.msg.setText(!TextUtils.isEmpty(msg.content) ? msg.content : msg.title);
        }
    }

    protected void getName(HomeTopBinding binding) {
        new NameReq().req(new ReqCallback<NameBean>() {
            @Override
            public void callback(boolean success, NameBean bean) {
                if (Constant.white) {
                    binding.name.setText(Utils.getPhone2());
                } else if (success) {
                    binding.name.setText(bean.name.toString());
                }
                boolean bo = false;
                try {
                    bo = bean.name.isFemale();
                    if (bo) {
                        binding.name.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.woman2, 0, 0, 0);
                    } else {
                        binding.name.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.avatar2, 0, 0, 0);
                    }
                } catch (Throwable e) {
                    binding.name.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.avatar2, 0, 0, 0);
                }
                if (getActivity() instanceof MainActivity) {
                    binding.name.setOnClickListener(v -> {
                        ((MainActivity) getActivity()).openDrawer();
                    });
                    ((MainActivity) getActivity()).setAvatar(binding.name.getText().toString(), bo);
                }
            }
        });
    }

    protected void getUnRead(HomeTopBinding binding) {
        binding.notify.setOnClickListener(v -> {
            Utils.toMsg();
        });
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                int n = new UnReadReq("SYSTEM").req();
                int m = new UnReadReq("USER").req();
                h.post(() -> {
                    int i = m + n;
                    if (i > 0) {
                        binding.num.setText((m + n) + "");
                        binding.num.setVisibility(View.VISIBLE);
                    } else {
                        binding.num.setVisibility(View.INVISIBLE);
                    }
                });
            }
        });
    }

    private final List<TextView> times = new ArrayList<>();
    private long left;
    UpdateRunnable runnable;

    protected void countDownTimeout() {

    }

    protected void startCountDown(CountDownBinding binding, long time) {
        left = time;
        binding.getRoot().setVisibility(View.VISIBLE);
        if (times.isEmpty()) {
            times.add(binding.tv2);
            times.add(binding.tv3);
            times.add(binding.tv4);
            times.add(binding.tv5);
        }
        if (runnable != null) {
            h.removeCallbacks(runnable);
        }
        runnable = new UpdateRunnable(binding);
        runnable.run();
    }

    class UpdateRunnable implements Runnable {
        CountDownBinding binding;

        UpdateRunnable(CountDownBinding binding) {
            this.binding = binding;
        }

        @Override
        public void run() {
            setTime(binding);
            if (--left >= 0) {
                h.postDelayed(this, 1000);
            } else {
                countDownTimeout();
            }
        }
    }

    private void setTime(CountDownBinding binding) {
        binding.hours.removeAllViews();
        left = Math.max(left, 0);
        int h = (int) (left / 3600);
        int min = (int) ((left - h * 3600) / 60);
        int sec = (int) (left - 3600 * h - 60 * min);

        int d = h / 24;
        if (d > 0) {
            String day = d + "";
            h = h % 24;
            for (char c : day.toCharArray()) {
                TextView tv = new TextView(getActivity());
                tv.setBackgroundResource(R.drawable.time_bg);
                tv.setTextColor(0xffF21B03);
                tv.setTextSize(15);
                tv.setGravity(Gravity.CENTER);
                tv.setText(String.valueOf(c));
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.rightMargin = Utils.dp2Px(getActivity(), 2);
                binding.hours.addView(tv, params);
            }
            TextView tv = new TextView(getActivity());
            tv.setTextColor(Color.BLACK);
            tv.setTextSize(15);
            tv.setGravity(Gravity.CENTER);
            tv.setText("días ");
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.rightMargin = Utils.dp2Px(getActivity(), 2);
            binding.hours.addView(tv, params);
        }
        String hour = h < 10 ? ("0" + h) : ("" + h);
        for (char c : hour.toCharArray()) {
            TextView tv = new TextView(getActivity());
            tv.setBackgroundResource(R.drawable.time_bg);
            tv.setTextColor(0xffF21B03);
            tv.setTextSize(15);
            tv.setGravity(Gravity.CENTER);
            tv.setText(String.valueOf(c));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.rightMargin = Utils.dp2Px(getActivity(), 2);
            binding.hours.addView(tv, params);
        }

        StringBuffer sb = new StringBuffer();
        if (min < 10) {
            sb.append("0");
        }
        sb.append(min);
        if (sec < 10) {
            sb.append("0");
        }
        sb.append(sec);
        char[] tmp = sb.toString().toCharArray();
        for (int i = 0; i < tmp.length; i++) {
            times.get(i).setText(String.valueOf(tmp[i]));
        }
    }

    protected void getLink(MeTouchBinding binding) {
        new LinkInfoReq().req(new ReqCallback<LinkInfoBean>() {
            @Override
            public void callback(boolean success, LinkInfoBean bean) {
                if (success && bean.isValid()) {
                    email = bean.info.email;
                    binding.email.setOnClickListener(v -> Utils.copy(email));
                    setMeValue(bean.info.email, R.string.me_email, binding.email);
                    setMeValue(bean.info.app, R.string.me_app, binding.app);
                    setMeValue(bean.info.phone, R.string.me_phone, binding.phone);
                }
            }
        });
    }

    private boolean setMeValue(String str, int id, TextView tv) {
        if (TextUtils.isEmpty(str)) {
            tv.setVisibility(View.GONE);
            return false;
        }
        String s = String.format(App.getApp().getString(id), str);
        tv.setVisibility(View.VISIBLE);
        tv.setText(s);
        return true;
    }
}
